
<template>
  <div class="box">
    <div class="btn-box">
      <div
        class="btn"
        :class="isPress ? '' : 'btn-normal'"
        @click="centralClick"
      ></div>
    </div>
    <div>
      <!-- <div class="camera_outer">
        <video
          hidden="true"
          id="videoCamera"
          :width="videoWidth"
          :height="videoHeight"
        ></video>
        <canvas
          hidden="true"
          style="display: none"
          id="canvasCamera"
          :width="videoWidth"
          :height="videoHeight"
        ></canvas>
        <div v-if="imgSrc" class="img_bg_camera">
          <img :src="imgSrc" alt="" class="tx_img" hidden="true" />
        </div>
      </div> -->
      <!-- <van-row type="flex" justify="center" style="padding: 20px">
        <van-col span="24" align="center"><van-button @click="switchD" style="width: 90%; margin: 5px;" type="primary" block="true" round>开启/关闭</van-button></van-col>
        <van-col span="24" align="center">
          <van-field v-model="imageNameD" label="文本" placeholder="请输入用户名" />
        </van-col>
        <van-col span="24" align="center"><van-button @click="addImageD" style="width: 90%; margin: 5px;" type="primary" block="true" round>录入</van-button></van-col>
      </van-row> -->
      <!-- <button @click="getCompetence()">打开摄像头</button>
      <button @click="stopNavigator()">关闭摄像头</button>
      <button @click="setImage()">拍照</button> -->
    </div>
    <keep-alive>
      <TabBar ref="tabBar" />
    </keep-alive>
  </div>
  <!-- <div>
    <van-uploader accept="audio/*" multiple :max-count="1" :after-read="setVoiceUpload" />
  </div> -->
  <!-- <div>
    <van-button @click="getTouchStart">Start</van-button>
    <van-button @click="getTouchEnd">Stop</van-button>
  </div> -->
</template>

<script>
import TabBar from "../components/TabBar.vue";
import Recorder from "js-audio-recorder";
import { Notify } from "vant";

function dataURItoBlob(dataURI) {
  var byteString = atob(dataURI.split(",")[1]);
  var mimeString = dataURI.split(",")[0].split(":")[1].split(";")[0];
  var ab = new ArrayBuffer(byteString.length);
  var ia = new Uint8Array(ab);
  for (var i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }
  return new Blob([ab], { type: mimeString });
}

let recorder = new Recorder({
  sampleBits: 16,
  sampleRate: 8000
});
export default {
  data() {
    return {
      isPress: false,
      loop: null, // 用于长按事件
      voiceInput: [],
      centralClickActive: false,

      videoWidth: 300,
      videoHeight: 300,
      imgSrc: "",
      imgBlob: null,
      thisCancas: null,
      thisContext: null,
      thisVideo: null,
      videoActive: false,
      timer: null,
      started : false,
      imageNameD: "",
    };
  },
  sockets: {
    connect: function () {
      console.log("socket connected");
    },
    openRecordFeedback: function (data) {
      console.log(
        'this method was fired by the socket server. eg: io.emit("customEmit", data)'
      );
    },
    onImageResp: function({data, success, code, message}) {
      if (success == false) {
        Notify({ type: "danger", message: message });
        return;
      }
      let feedbackText = data.feedbackText;
      console.log("onImageResp, feedbackText: " + feedbackText);
    },
    onRecordRestartResp: function({data, success, code, message}) {
      if (success == false) {
        Notify({ type: "danger", message: message });
        return;
      }
      console.log("onRecordRestartResp, result: " + data);
    },
    parseVoiceResp: function ({ data, success, code, message }) {
      if (success == false) {
        Notify({ type: "danger", message: message });
        return;
      }
      let text = data.text;
      let binary = data.binary;
      let chinese = data.chinese;
      console.log("parseVoiceResp: " + text);
      this.sppechHandler(data);
    },
  },
  mounted() {
    let userToken = this.$store.state.user.userToken;
    if(userToken == null || userToken == "") {
      this.$router.push({path: "/login"});
    }
    this.$store.dispatch("group/listGroup");
    // this.getCompetence();
    // this.timer = setInterval(this.setImage, 2000);
  },
  methods: {
    switchD() {
      let timerHandler = this.$store.state.record.timerHandler
      let data
      if(timerHandler == null) {
        data = {
            chinese: "开启",
            text: "openRecord",
            binary: null,
        }
      } else {
        data = {
            chinese: "关闭",
            text: "closeRecord",
            binary: null,
        }
      }
      this.sppechHandler(data);
    },
    addImageD() {
      
    },
    onSubmit(e) {},
    setVoiceUpload(file) {
      //file: {file: File, status: '', message: '', content: 'data:audio/aac;base64,//FMgFY//CERRQAUUAFG//EKWlpa…93hWtdj87+R1oa1VT51LmkxK/PKBOmi5mWqCPTRLMEMft84MH'}
      console.log(file);
      var fileBytes = file.content;
      console.log("setVoiceUpload");
      this.$socket.emit("parseVoice", { voiceFile: fileBytes });
    },
    centralClick() {
      console.log("enter centralClick, active: " + this.centralClickActive);
      if (this.centralClickActive) {
        this.getTouchEnd();
        this.centralClickActive = false;
      } else {
        this.getTouchStart();
        this.centralClickActive = true;
      }
    },
    getTouchStart() {
      var that = this;
      console.log("recorder.start");
      console.log(this.$store.state.user.userToken);
      recorder.start();
      // clearTimeout(this.loop);
      // this.loop = setTimeout(function () {
      //   // 长按操作
      //   console.log("长按");
      // }, 500);
      // this.isPress = true;
      // this.$socket.emit("openRecord", {data: "s"});
    },
    getTouchEnd() {
      recorder.stop();

      //for debug
      // recorder.play();
      let groupToken = this.$store.state.group.selectedGroupToken;
      let userToken = this.$store.state.user.userToken;
      console.log("recorder.stop" + ", groupToken: " + groupToken, ", userToken: " + userToken);
      let wavBlob = recorder.getWAVBlob();
      // let callback = this.sppechHandler;
      // this.$store.dispatch("record/parse", {file: blob, callback: callback});
      console.log(wavBlob);
      var fileReader = new FileReader();
      let sock = this.$socket;
      fileReader.onload = function (event) {
        console.log("fileReader onload");
        var arrayBuffer = event.target.result;
        sock.emit("parseVoice", { voiceFile: arrayBuffer, groupToken:  groupToken});
      };
      fileReader.readAsArrayBuffer(wavBlob);

      //Start debug code
      // if(!this.started) {
      //   let userToken = this.$store.state.user.userToken;
      //   let groupToken = this.$store.state.group.selectedGroupToken;
        // this.$socket.emit("onRecordRestart", {
        //   userToken : userToken,
        //   groupToken: groupToken
        // });
        // let data = {
        //   chinese: "开启",
        //   text: "openRecord",
        //   binary: null,
        // }
        // this.sppechHandler(data);
        // this.started = true;
      // } else {
        // let data = {
        //   chinese: "关闭",
        //   text: "closeRecord",
        //   binary: null,
        // }
        // this.sppechHandler(data);
        // this.started = false;
      // }
      //End debug code

      // clearTimeout(this.loop);
      // this.isPress = false;
    },
    sppechHandler({ text, chinese, binary }) {
      if (!text) {
        return;
      }
      console.log("receive sppechHandler, " + text + " chinese: " + chinese);
      let timerHandler;
      let thisVideo;
      switch (text) {
        case "openRecord":
          this.$refs.tabBar.setVideoActive(true);
          // thisVideo = this.$store.state.record.thisVideo;
          // console.log(thisVideo);
          // thisVideo.play();
          // console.log("openRecord");
          // timerHandler = this.$store.state.record.timerHandler;
          // if(timerHandler!= null) {
          //   clearInterval(timerHandler);
          //   this.$store.commit("record/setTimerHandler", {timerHandler: null});
          // }
          // let timer = setInterval(this.setImage, 2000);
          // this.$store.commit("record/setTimerHandler", {timerHandler: timer});
          // console.log("timer: ", timerHandler);
          break;
        case "closeRecord":
          this.$refs.tabBar.setVideoActive(false);
          // timerHandler = this.$store.state.record.timerHandler;
          // if(timerHandler != null) {
          //   console.log("timer: ", timerHandler);
          //   clearInterval(timerHandler);
          //   this.$store.commit("record/setTimerHandler", {timerHandler: null});
          // }
          // console.log("closeRecord");
          // // this.videoActive = false;
          // thisVideo = this.$store.state.record.thisVideo;
          // thisVideo.pause();
          break;
        case "addImage":
          console.log("addImage ok");
          break;
        default:
          return;
      }
    },
    setImage() {
      // console.log("setImage, active: ", this.videoActive);
      // if(!this.videoActive) {
      //   return;
      // }
      console.log("Enter setImage");
      let _this = this;
      // 点击，canvas画图
      let thisContext = this.$store.state.record.thisContext;
      let thisVideo = this.$store.state.record.thisVideo;
      let thisCancas = this.$store.state.record.thisCancas;

      thisContext.drawImage(
        thisVideo,
        0,
        0,
        this.$store.state.record.videoWidth,
        this.$store.state.record.videoHeight
      );
      // 获取图片base64链接
      var image = thisCancas.toDataURL("image/jpeg");

      this.imgSrc = image;
      let userToken = this.$store.state.user.userToken;
      let groupToken = this.$store.state.group.selectedGroupToken;
      var blob = dataURItoBlob(image);
      this.$socket.emit("onImage", { 
        imageBytes: blob, 
        extension: "jpeg",
        userToken: userToken,
        groupToken : groupToken
      });
      // this.send();
      // this.$emit("refreshDataList", this.imgSrc);
    },
    // getCompetence() {
    //   console.log("getCompetence");
    //   var _this = this;
    //   this.thisCancas = document.getElementById("canvasCamera");
    //   this.thisContext = this.thisCancas.getContext("2d");
    //   this.thisVideo = document.getElementById("videoCamera");
    //   this.$store.commit("record/setVideoContext", {
    //     thisCancas: this.thisCancas,
    //     thisContext: this.thisContext,
    //     thisVideo: this.thisVideo
    //   });
    //   let store = this.$store;
    //   // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
    //   if (navigator.mediaDevices === undefined) {
    //     navigator.mediaDevices = {};
    //   }
    //   // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
    //   // 使用getUserMedia，因为它会覆盖现有的属性。
    //   // 这里，如果缺少getUserMedia属性，就添加它。
    //   if (navigator.mediaDevices.getUserMedia === undefined) {
    //     navigator.mediaDevices.getUserMedia = function (constraints) {
    //       // 首先获取现存的getUserMedia(如果存在)
    //       var getUserMedia =
    //         navigator.webkitGetUserMedia ||
    //         navigator.mozGetUserMedia ||
    //         navigator.getUserMedia;
    //       // 有些浏览器不支持，会返回错误信息
    //       // 保持接口一致
    //       if (!getUserMedia) {
    //         return Promise.reject(
    //           new Error("getUserMedia is not implemented in this browser")
    //         );
    //       }
    //       // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
    //       return new Promise(function (resolve, reject) {
    //         getUserMedia.call(navigator, constraints, resolve, reject);
    //       });
    //     };
    //   }
    //   var constraints = {
    //     audio: false,
    //     video: {
    //       width: 300,
    //       height: 300,
    //       transform: "scaleX(-1)",
    //     },
    //   };
    //   navigator.mediaDevices
    //     .getUserMedia(constraints)
    //     .then(function (stream) {
    //       // 旧的浏览器可能没有srcObject
    //       if ("srcObject" in store.state.record.thisVideo) {
    //         store.state.record.thisVideo.srcObject = stream;
    //       } else {
    //         // 避免在新的浏览器中使用它，因为它正在被弃用。
    //         store.state.record.thisVideo.src = window.URL.createObjectURL(stream);
    //       }
    //       store.state.record.thisVideo.onloadedmetadata = function (e) {
    //         // _this.thisVideo.play();
    //       };
    //     })
    //     .catch((err) => {
    //       console.log(err);
    //     });
    // }
  },
  components: {
    TabBar,
  },
};
</script>

<style lang="css" scoped>
.box {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: ghostwhite;
}
.btn-box {
  width: 200px;
  height: 200px;
  border-radius: 100px;
  border: 1px solid #000;
  background: #fff;
}
.btn {
  position: absolute;
  width: 120px;
  height: 120px;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  margin: auto;
  border-radius: 60px;
  background-color: skyblue;
  border: 1px solid #fff;
}
.btn-normal {
  box-shadow: 2px 2px 5px #000;
}
</style>
